<?php
class install{
	public function __construct(){
	
	}
	
	//检测数据库信息是否正确
	public function get_info($arr){
		
		$mysqli=@new mysqli($arr['host'],$arr['user_name'],$arr['user_pwd'],$arr['db_name']);
		if($mysqli->connect_errno){
			return array('status'=>0,'msg'=>'数据库连接失败！','other'=>array());
		}
		$query="show tables";
		$data=array('status'=>1,'msg'=>'数据库连接成功！','other'=>array());
		if($result=$mysqli->query($query)){
			
			while($row=$result->fetch_row()){
				$data['other'][]=$row[0];
			}
			
			$result->free();
		}
		$mysqli->close();
		
		return $data;
	}
	public function make($arr){
		$mysqli=@new mysqli($arr['host'],$arr['user_name'],$arr['user_pwd'],$arr['db_name']);
		if($mysqli->connect_errno){
			return array('status'=>0,'msg'=>'数据库连接失败！','other'=>array());
		}
		$mysqli->query("set names utf8");
		if($arr['type']==1){
			if($arr['data']){
				$arr['data']=$this->treat_sql($arr['data']);

				$r=$mysqli->multi_query($arr['data']);
				if($r){
					$ret=array('status'=>1,'msg'=>'数据插入成功！','other'=>array());
				}else{
					$ret=array('status'=>0,'msg'=>'数据插入失败！','other'=>array());
				}
				
			}else{
				$ret=array('status'=>0,'msg'=>'数据内容为空！','other'=>array());
			}
		}else{
			if($arr['file'] && file_exists($arr['file'])){
				$data=file_get_contents($arr['file']);
				if($data){
					$data=$this->treat_sql($data);
					$r=$mysqli->multi_query($data);
					if($r){
						$ret=array('status'=>1,'msg'=>'数据插入成功！','other'=>array());
					}else{
						$ret=array('status'=>0,'msg'=>'数据插入失败！','other'=>array());
					}
				}else{
					$ret=array('status'=>0,'msg'=>'sql文件内容为空！','other'=>array());
				}
			}else{
				$ret=array('status'=>0,'msg'=>'sql文件不存在！','other'=>array());
			}
		}
		$mysqli->close();
		return $ret;
	}
	//生成配置文件
	public function create_config_file($arr){

		$search=array(
			'{%host%}','{%user%}','{%pwd%}','{%db%}','{%prefix%}','{%url%}','{%cookie_domain%}'
		);
		$replace=array(
			$arr['host'],$arr['user_name'],$arr['user_pwd'],$arr['db_name'],$arr['db_pre'],$arr['url'],$arr['cookie_domain']
		);
		$sample=file_get_contents('config.inc_sample.php');
		
		$content=str_replace($search,$replace,$sample);
		

		return file_put_contents('config.inc.php',$content);
	}
	private function treat_sql($content){
		return $content;
		$string='';
		
		$string=preg_replace('/\n{2,}/',"\n",$content);//去除空行
		
		$arr=array();
		$arr=(array) explode("\n",$string);
		$arr2=array();
		foreach($arr as $v){
			if(trim($v)=='' or substr(trim($v),0,2)=='--') continue;
			$arr2[]=$v;
		}
		
		return implode("\n",$arr2);
	}
//
}